package com.cictec.middleware.gps.engine.position.handler.alarms;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.Constants;
import com.cictec.middleware.commons.utils.DateUtils;
import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.commons.utils.PropertiesUtils;
import com.cictec.middleware.core.entity.BusLineStation;
import com.cictec.middleware.core.entity.WarnMsg;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.TimingPoint;
import com.cictec.middleware.gps.engine.exception.BusPositionWarnHandlerException;
import com.cictec.middleware.gps.engine.position.handler.BusPositionAlarmsHandler;
import com.cictec.middleware.gps.service.BusLineService;
import com.cictec.middleware.gps.service.WarnMsgService;

/**
 * 站点停战时间过长报警（压站报警）
 * @author ql
 * @date 2017年9月26日
 */
@Component
public class StationStopTooLongWarnHandler implements WarnHandler {

	private static Logger logger = LoggerFactory.getLogger(BusPositionAlarmsHandler.class);
	
	@Autowired
	private WarnMsgService warnMsgService;
	@Autowired
	private BusLineService busLineService;

	
	/** 压站的时间阈值 单位秒，过站时间小于该阈值，认为甩站。*/
	private static int keepLongThrohold = 5*60;
	
	@Override
	public String getWarnType() {
		return Constants.VAL_BUS_STATUS_14;
	}
	
	@Override
	public void onHandler(BusInstance busInstance) throws BusPositionWarnHandlerException {
		logger.debug("【压站报警信息处理】");
		
		if(isStopWarn(busInstance)){
			stopWarn(busInstance);
//			return;
		}
		
		
		if(busInstance.isInStation()){
			
			// 当前站点信息
			TimingPoint currentStation = busInstance.getCurrentStation();
			if(currentStation == null){
				return;
			}
			keepLongThrohold = PropertiesUtils.getIntValue("system.parameter.warn.keepLongThrohold", keepLongThrohold);
			
			long secondsInterval = DateUtils.secondInterval(busInstance.getTime(), currentStation.getTime());
//			secondsInterval = 400;
//			System.out.println("当前时间："+busInstance.getTime());
//			System.out.println("当前进站时间："+currentStation.getTime());
			if(busInstance.getTime().getTime() > currentStation.getTime().getTime() 
					&& secondsInterval > keepLongThrohold){
				
				startWarn(busInstance);
			}
			
		}
	}
	
	
	
	/**
	 * 压站停止条件：非运营、偏线 、最后一站 、线路切换 、相同进站状态，不同站点信息 、出站状态信息上传
	 * 
	 * @param busInstance
	 * @return
	 */
	private boolean isStopWarn(BusInstance busInstance) {
		// 出站状态信息上传
		if (!busInstance.isInStation()) {
			return true;
		}
		
		// 偏线、非运营
		if (busInstance.isInDeviate() || !busInstance.isInOperateTime()) {
			// 如果是偏线，默认停止压站报警
			return true;
		}

		// 线路切换
		TimingPoint prePoint = busInstance.getTimingPoint(-1);
		if (!prePoint.getLineType().equals(busInstance.getLineType())) {
			return true;
		}

		// 最后一站 
		if (busInstance.isEnterOut()) {
			TimingPoint currentStation = busInstance.getCurrentStation();
			boolean isLastStation = busLineService.isLastLineStation(currentStation.getLineUuid(), currentStation.getStationLineTypeOrg(), currentStation.getStationLineSeqOrg());
			if (isLastStation) {
				return true;
			}
		}
		
		// 相同进站状态，不同站点信息（进出站没有上传 出站信息）
		if (busInstance.isEnterOut()) {
			TimingPoint preStation = busInstance.getPreStation();
			TimingPoint currentStation = busInstance.getCurrentStation();
			if(preStation != null){
				if(preStation.isInStation() && currentStation.isInStation()
						&& !preStation.getStationLineSeqOrg().equals(currentStation.getStationLineSeqOrg())
						){
					return true;
				}
			}
		}
		
		return false;
	}

	public void startWarn(BusInstance busInstance){
		TimingPoint point = busInstance.getCurrentStation();
		BusLineStation station = busLineService.getLineStationByStationSeq(point.getLineUuid(), point.getStationLineTypeOrg(), point.getStationLineSeqOrg());
		
		//在站时间超过压站的阈值，判定为压站。
		WarnMsg warnMsg = new WarnMsg();
		warnMsg.setWarnBusUuid(busInstance.getBusUuid());
		warnMsg.setWarnDevUuid(busInstance.getDevUuid());
		warnMsg.setWarnDrvUuid(busInstance.getDriverUuid());

		warnMsg.setWarnLineUuid(busInstance.getLineUuid());
		warnMsg.setWarnType(Constants.VAL_BUS_STATUS_14);
		warnMsg.setWarnStartLat(busInstance.getLatitude());
		warnMsg.setWarnStartLng(busInstance.getLongitude());
//		warnMsg.setWarnStartOdometer(enter.getPositionOdometer());
		warnMsg.setWarnStartTime(DateUtils.formatDateTimes(busInstance.getTime()));
		
//		warnMsg.setWarnEndOdometer(leave.getPositionOdometer());
//		warnMsg.setWarnEndTime(DateUtils.formatDateTimes(currentTime));
//		warnMsg.setReferenceUuid(enter.getLineStationUuid());
		
		warnMsg.setWarnStaUuid(station.getLsStaUuid());
		warnMsg.setWarnStorageTime(DateUtils.formatDateTimes(new Date()));
//		warnMsg.setWarnOperStatus(Constants.VAL_BUS_OPER_STATUS_1);
		warnMsg.setWarnOperStatus(busInstance.getStatusInOperateTime());
		
		warnMsgService.saveWarn(warnMsg);	
		WarnMsg cWarnMsg = busInstance.getWarnsByWarnType(Constants.VAL_BUS_STATUS_14);
		if(cWarnMsg == null){
			busInstance.setWarns(Constants.VAL_BUS_STATUS_14, warnMsg);
		}else{
			// 先停止之前的在 添加新的
			stopWarn(busInstance);
			busInstance.setWarns(Constants.VAL_BUS_STATUS_14, warnMsg);
		}
		
		logger.debug("【压站报警】{}-{} 站内甩站,大于停留设定阀值{}秒，该站点 lineType:{}, seq{}", busInstance.getDevCode(), busInstance.getBusNumber(), busInstance.getLineType(), busInstance.getStationSeq());
	}
	
	
	
	@Override
	public void stopWarn(BusInstance busInstance) {
		WarnMsg warnMsg = busInstance.getWarnsByWarnType(Constants.VAL_BUS_STATUS_14);
		if (warnMsg != null) {

			warnMsg.setWarnEndLat(busInstance.getLatitude());
			warnMsg.setWarnEndLng(busInstance.getLongitude());
			warnMsg.setWarnEndTime(DateUtils.formatDateTimes(busInstance.getTime()));

			warnMsg.setWarnStorageTime(DateUtils.formatDateTimes(new Date()));
//			warnMsg.setWarnOperStatus(Constants.VAL_BUS_OPER_STATUS_1);
			warnMsg.setWarnOperStatus(busInstance.getStatusInOperateTime());
			warnMsg.setWarnDuration(PMSUtils.isNull(DateUtils.secondInterval(warnMsg.getWarnStartTime(), warnMsg.getWarnEndTime())));
			warnMsgService.saveWarn(warnMsg);

			busInstance.setWarns(Constants.VAL_BUS_STATUS_14, null);
		}
	}

}
